# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
@File    :   server.py
@Time    :   2021/09/25 15:54:16
@Author  :   Jumping
@Version :   1.5
@Contact :   xjp17@mails.tsinghua.edu.cn
@License :   (C)Copyright 2020-2025
@Desc    :   None

function :   网页主程序
"""

from flask import Flask, jsonify, render_template, request, redirect, make_response, flash, session
from werkzeug.utils import secure_filename
import json
import csv
import time
import os


OWN_FILE = 'static/data/random_data.txt'
UPLOAD_FOLDER_C = 'static/file_upload/'
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)  # 每一次服务器启动后，SECRET_KEY(盐)不一样
app.config['OWN_FILE'] = OWN_FILE
app.config['UPLOAD_FOLDER_C'] = UPLOAD_FOLDER_C
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024
data = []

@app.route('/')
def main_page():
    session.clear()  # 清除所有session
    return render_template('main.html')

@app.route('/load_data', methods=['POST'])
def load_data():
    f = open(app.config['OWN_FILE'],'r')
    lines = f.readlines()
    data = []
    for line in lines:
        try:
            line_temp = line.split(',')
            i = int(line_temp[0])
            data.append([i,int(line_temp[1])])
        except:
            pass
    a = {
        "value": data
    }
    return json.dumps(a)

@app.route('/help')
def help():
    session.clear()  # 清除所有session
    return render_template('help.html')

@app.route('/submit_task', methods=['POST'])
def submit_task():
    file1 = request.files['file']
    filename = secure_filename(file1.filename)
    print(filename)
    file1.save(os.path.join(app.config['UPLOAD_FOLDER_C'], filename))
    f = open(os.path.join(app.config['UPLOAD_FOLDER_C'], filename),'r')
    lines = f.readlines()
    data = []
    for line in lines:
        try:
            line_temp = line.split(',')
            i = int(line_temp[0])
            data.append([i,int(line_temp[1])])
        except:
            pass
    a = {
        "value": data,
        "msg":"读取成功"
    }
    return json.dumps(a)

@app.route('/data_start', methods=['POST'])
def data_start():

    a = {
            "msg":"开启读取"
        }
    return json.dumps(a)

@app.route('/data_read', methods=['POST'])
def data_read():
    a = {
            "msg":"sucess"
        }
    return json.dumps(a)

@app.route('/data_pause', methods=['POST'])
def data_pause():
    a = {
            "msg":"暂停读取"
        }
    return json.dumps(a)

@app.route('/data_stop', methods=['POST'])
def data_stop():
    a = {
            "msg":"停止读取"
        }
    return json.dumps(a)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)
